<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="formData" ref="formDataRef">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="模型名称" prop="moduleName">
            <el-input v-model="formData.moduleName" placeholder="模型名称" clearable style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="模型类型" prop="moduleType">
            <el-select v-model="formData.moduleType" placeholder="模型类型" clearable style="width: 100%">
              <el-option label="列表" value="list"></el-option>
              <el-option label="详情" value="detail"></el-option>
              <el-option label="单页" value="page"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="状态" clearable style="width: 100%">
              <el-option label="正常" :value="1"></el-option>
              <el-option label="停用" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <ButtonGroup ref="btnGroupRef" @on-search="search" @on-reset="resetSearch">
            <template v-slot:hole>
              <el-button type="primary" size="small" @click="handleAdd">新增模型</el-button>
              <el-button type="danger" size="small" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
            </template>
          </ButtonGroup>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <BaseTable
      :table-columns="tableColumns"
      :table-data="tableData"
      :options="tableOptions"
      :total="pages.total"
      v-model:page-num="pages.pageNum"
      v-model:page-size="pages.pageSize"
      @turnOn="search"
      :tableLoading="tableLoading"
      @selectionChange="handleSelectionChange"
    >
      <template v-slot:operation="{ row }">
        <el-button type="primary" text @click="handleView(row)">新增数据</el-button>
        <el-button type="primary" text @click="handleEdit(row)">编辑模型</el-button>
        <el-button type="danger" text @click="handleDelete(row)">删除</el-button>
      </template>
      <template v-slot:moduleType="{ row }">
        <el-tag :type="getModuleTypeTagColor(row.moduleType)">
          {{ transferModuleType(row.moduleType) }}
        </el-tag>
      </template>
      <template v-slot:status="{ row }">
        <el-tag :type="row.status === 1 ? 'success' : 'danger'">
          {{ row.status === 1 ? "正常" : "停用" }}
        </el-tag>
      </template>
    </BaseTable>

    <!-- 弹窗 -->
    <Dialog ref="dialogRef" :title="dialogOptions.title" :width="dialogOptions.width" @close="handleDialogClose" @confirm="handleDialogConfirm">
      <template v-slot:content>
        <el-form :model="diaFormData" :rules="diaFormDataRules" ref="diaFormDataRef" label-width="120px">
          <el-form-item label="模型名称" prop="moduleName">
            <el-input v-model="diaFormData.moduleName" placeholder="请输入模型名称"></el-input>
          </el-form-item>
          <el-form-item label="模型类型" prop="moduleType">
            <el-select v-model="diaFormData.moduleType" placeholder="请选择模型类型" style="width: 100%">
              <el-option label="列表" value="list"></el-option>
              <el-option label="详情" value="detail"></el-option>
              <el-option label="单页" value="page"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="diaFormData.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="正常" :value="1"></el-option>
              <el-option label="停用" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="列表模板名称" prop="listTemplateName" v-if="diaFormData.moduleType === 'list'">
            <el-input v-model="diaFormData.listTemplateName" placeholder="请输入列表模板名称（可选）"></el-input>
          </el-form-item>
          <el-form-item label="列表模板ID" prop="listTemplateId" v-if="diaFormData.moduleType === 'list'">
            <el-input v-model="diaFormData.listTemplateId" placeholder="请输入列表模板ID（可选）"></el-input>
          </el-form-item>
          <el-form-item label="单页模板名称" prop="detailTemplateName">
            <el-input v-model="diaFormData.detailTemplateName" placeholder="请输入单页模板名称（可选）"></el-input>
          </el-form-item>
          <el-form-item label="单页模板ID" prop="detailTemplateId">
            <el-input v-model="diaFormData.detailTemplateId" placeholder="请输入单页模板ID"></el-input>
          </el-form-item>
        </el-form>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { IModuleType } from "#/common";
import BaseTable from "@/components/BaseTable/index.vue";
import Dialog from "@/components/Dialog/index.vue";
import ButtonGroup from "@/components/ButtonGroup/index.vue";
import { resetForm } from "@/utils/tools";
import { getModuleList, createModule, updateModule, deleteModule, batchDeleteModules } from "@/api/webbase";
import { useRouter } from "vue-router";

// ------- 响应式数据 -------
const formData = ref({
  moduleName: "",
  moduleType: "",
  status: ""
});

const pages = ref({
  pageSize: 10,
  pageNum: 1,
  total: 0
});

const tableData = ref([]);
const tableLoading = ref(false);
const selectedRows = ref([]);

// 弹窗相关
const diaFormData = ref<IModuleType>({
  moduleName: "",
  moduleType: "list",
  status: 1,
  listTemplateName: "",
  listTemplateId: "",
  detailTemplateName: "",
  detailTemplateId: ""
});

const dialogOptions = ref({
  title: "新增模型",
  width: "600px"
});

const isEdit = ref(false);
const editId = ref("");

// ------- 表单验证规则 -------
const diaFormDataRules = {
  moduleName: [{ required: true, message: "请输入模型名称", trigger: "blur" }],
  moduleType: [{ required: true, message: "请选择模型类型", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }]
};
// 页面绑定分类，分类下跟着数据。所以数据也就跟着页面，
// 模型用来控制页面样式，选择模板？
//
// ------- 表格配置 -------
const tableColumns = [
  {
    label: "模型名称",
    prop: "moduleName",
    showOverflowTooltip: true
  },
  {
    label: "模型类型",
    prop: "moduleType",
    slotable: true,
    width: 86
  },
  {
    label: "状态",
    prop: "status",
    slotable: true,
    width: 86
  },
  {
    label: "列表模板名称",
    prop: "listTemplateName",
    showOverflowTooltip: true
  },
  {
    label: "详情模板名称",
    prop: "detailTemplateName",
    showOverflowTooltip: true
  }
];

const tableOptions = {
  showSelect: true,
  showOption: true,
  optionWidth: 320
};

const router = useRouter();

// ------- refs -------
const formDataRef = ref<FormInstance>();
const diaFormDataRef = ref<FormInstance>();
const dialogRef = ref();
const btnGroupRef = ref();

// ------- 方法 -------

/**
 * 生成模板ID
 * @param prefix ID前缀
 * @returns 生成的模板ID
 */
const generateTemplateId = (prefix: string): string => {
  const timestamp = Date.now();
  const randomStr = Math.random().toString(36).substring(2, 8);
  return `${prefix}_${timestamp}_${randomStr}`;
};

/**
 * 搜索数据
 */
const search = async () => {
  try {
    tableLoading.value = true;
    const params = {
      ...pages.value,
      ...formData.value
    };
    const res = await getModuleList(params);
    tableData.value = res.data.list || [];
    pages.value.total = res.data.total || 0;
  } catch (error) {
    ElMessage.error("查询失败");
  } finally {
    tableLoading.value = false;
  }
};

/**
 * 重置搜索
 */
const resetSearch = () => {
  resetForm(formDataRef.value);
  search();
};

/**
 * 处理表格选择变化
 * @param selection 选中的行数据
 */
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

/**
 * 新增模型
 */
const handleAdd = () => {
  isEdit.value = false;
  dialogOptions.value.title = "新增模型";
  resetDialogForm();
  // 自动生成detailTemplateId
  diaFormData.value.detailTemplateId = generateTemplateId("detail");
  // 如果默认是list类型，也生成listTemplateId
  if (diaFormData.value.moduleType === "list") {
    diaFormData.value.listTemplateId = generateTemplateId("list");
  }
  dialogRef.value.visiableDialog();
};

/**
 * 编辑模型
 * @param row 行数据
 */
const handleEdit = (row: any) => {
  isEdit.value = true;
  editId.value = row._id;
  dialogOptions.value.title = "编辑模型";
  diaFormData.value = {
    moduleId: row.moduleId || row._id,
    moduleName: row.moduleName,
    moduleType: row.moduleType,
    status: row.status,
    listTemplateName: row.listTemplateName || "",
    listTemplateId: row.listTemplateId || "",
    detailTemplateName: row.detailTemplateName || "",
    detailTemplateId: row.detailTemplateId || ""
  };
  dialogRef.value.visiableDialog();
};

/**
 * 删除模型
 * @param row 行数据
 */
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm("确定要删除该模型吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    await deleteModule(row._id);
    ElMessage.success("删除成功");
    search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

/**
 * 查看详情的操作
 * @param row
 */
const handleView = (row: IModuleType) => {
  router.push({
    path: "/model-list",
    query: {
      moduleId: row.moduleId
    }
  });
  return;
  if (row.moduleType === "list") {
  } else if (row.moduleType === "page") {
    router.push({
      path: "/model-page",
      query: {
        moduleId: row.moduleId
      }
    });
  }
};

/**
 * 批量删除
 */
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedRows.value.length}条数据吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    const ids = selectedRows.value.map((row: any) => row._id);
    await batchDeleteModules(ids);
    ElMessage.success("批量删除成功");
    search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量删除失败");
    }
  }
};

/**
 * 重置弹窗表单
 */
const resetDialogForm = () => {
  diaFormData.value = {
    moduleName: "",
    moduleType: "list",
    status: 1,
    listTemplateName: "",
    listTemplateId: "",
    detailTemplateName: "",
    detailTemplateId: ""
  };
  diaFormDataRef.value?.clearValidate();
};

/**
 * 转换模型类型显示文本
 * @param type 模型类型
 * @returns 显示文本
 */
const transferModuleType = (type: string) => {
  if (type === "list") {
    return "列表";
  } else if (type === "detail") {
    return "详情";
  } else if (type === "page") {
    return "单页";
  }
};

/**
 * 获取模型类型标签颜色
 * @param type 模型类型
 * @returns 标签颜色类型
 */
const getModuleTypeTagColor = (type: string) => {
  switch (type) {
    case "list":
      return "primary"; // 蓝色
    case "detail":
      return "success"; // 绿色
    case "page":
      return "warning"; // 橙色
    default:
      return "info"; // 灰色
  }
};

/**
 * 弹窗确认事件
 */
const handleDialogConfirm = async () => {
  try {
    await diaFormDataRef.value?.validate();

    if (isEdit.value) {
      await updateModule(editId.value, diaFormData.value);
      ElMessage.success("更新成功");
    } else {
      await createModule(diaFormData.value);
      ElMessage.success("创建成功");
    }

    dialogRef.value.invisiableDialog();
    search();
  } catch (error) {
    ElMessage.error(isEdit.value ? "更新失败" : "创建失败");
    dialogRef.value.clearLoading();
  }
};

/**
 * 弹窗关闭事件
 */
const handleDialogClose = () => {
  resetDialogForm();
};

// ------- 监听器 -------

/**
 * 监听模型类型变化，自动生成或清空相应的模板ID
 */
watch(
  () => diaFormData.value.moduleType,
  (newType, oldType) => {
    if (newType !== oldType) {
      // 总是重新生成detailTemplateId
      diaFormData.value.detailTemplateId = generateTemplateId("detail");

      if (newType === "list") {
        // 切换到list类型时，生成listTemplateId
        diaFormData.value.listTemplateId = generateTemplateId("list");
      } else {
        // 切换到非list类型时，清空list相关字段
        diaFormData.value.listTemplateId = "";
        diaFormData.value.listTemplateName = "";
      }
    }
  }
);

// ------- 生命周期 -------
onMounted(() => {
  search();
});
</script>

<style scoped lang="less">
.app-container {
  padding: 20px;
}
</style>
